package com.iven.xie.encrypt.tool;


import com.iven.xie.encrypt.bean.EncryptBody;
import com.iven.xie.encrypt.config.EncryptBodyConfig;
import com.iven.xie.encrypt.enums.DecryptBodyMethod;
import com.iven.xie.encrypt.exception.DecryptBodyFailException;
import com.iven.xie.encrypt.exception.DecryptMethodNotFoundException;
import com.iven.xie.encrypt.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 请求数据的加密信息解密处理<br>
 *
 * @author iven.xie
 */
@Slf4j
@Component
public class DecryptRequestBodyService {

    @Autowired
    private EncryptBodyConfig config;

    /**
     * 选择加密方式并进行解密
     *
     * @param encryptBody 加密信息
     * @return 解密结果
     */
    public String switchDecrypt(EncryptBody encryptBody) {
        DecryptBodyMethod method = encryptBody.getDecryptBodyMethod();
        if (method == null) {
            throw new DecryptMethodNotFoundException();
        }
        if (method == DecryptBodyMethod.BASE64) {
            return BASE64EncryptUtil.decrypt(encryptBody.getFormatStringBody());
        }
        String key = encryptBody.getKey();
        if (method == DecryptBodyMethod.DES) {
            key = CheckUtils.checkAndGetKey(config.getDesKey(), key, "DES-KEY");
            return DESEncryptUtil.decrypt(encryptBody.getFormatStringBody(), key);
        }
        if (method == DecryptBodyMethod.AES) {
            key = CheckUtils.checkAndGetKey(config.getAesKey(), key, "AES-KEY");
            return AESEncryptUtil.decrypt(encryptBody.getFormatStringBody(), key);
        }
        if (method == DecryptBodyMethod.RSA) {
            key = CheckUtils.checkAndGetKey(config.getRsaPrivateKey(), key, "RSA-PRIVATE-KEY");
            return RSAEncryptUtil.decrypt(encryptBody.getFormatStringBody(), key);
        }
        throw new DecryptBodyFailException();
    }
}
